package com.mvp.lt.airlineview.gismap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.mvp.lt.airlineview.R;
import com.mvp.lt.airlineview.agorartc.VideoChatViewActivity;
import com.mvp.lt.airlineview.utils.LocationAmpUtils;
import com.mvp.lt.airlineview.utils.ToastUtils;
import com.shuyu.gsyvideoplayer.utils.NetworkUtils;

import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.MapTileProviderBasic;
import org.osmdroid.tileprovider.modules.ArchiveFileFactory;
import org.osmdroid.tileprovider.modules.IArchiveFile;
import org.osmdroid.tileprovider.modules.OfflineTileProvider;
import org.osmdroid.tileprovider.tilesource.FileBasedTileSource;
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.SimpleRegisterReceiver;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.MapTileIndex;
import org.osmdroid.views.CustomZoomButtonsController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.TilesOverlay;
import org.osmdroid.views.overlay.compass.CompassOverlay;
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider;
import org.osmdroid.views.overlay.gestures.RotationGestureOverlay;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;

import java.io.File;
import java.util.Objects;
import java.util.Set;

/**
 * @author LiuTao
 * @description:
 * @date : 2021/4/21 9:37
 */
public class GisMapActivity extends AppCompatActivity {

    private CustomsOsmdroidMapConfig config = new CustomsOsmdroidMapConfig();

    private RotationGestureOverlay mRotationGestureOverlay;
    private ScaleBarOverlay mScaleBarOverlay;
    private CompassOverlay mCompassOverlay;
    private MyLocationNewOverlay mLocationOverlay;
    private MapView mMapView;

    public static void show(Context context) {
        Intent intent = new Intent(context, GisMapActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Context ctx = getApplicationContext();
        Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
        setContentView(R.layout.activity_gis_map);

        mMapView = findViewById(R.id.map);

        //手控放大缩小
        mMapView.setMultiTouchControls(true);
//        //地图缩放min&max以及初始缩放比例
//        mapView.setMaxZoomLevel((double) 20);
        mMapView.setMinZoomLevel((double) 4);
//        mMapView.setTileSource(TileSourceFactory.MAPNIK);
        setMapSources();
        IMapController mapController = mMapView.getController();
        mapController.setZoom(15);
        //设置中心点 112.98068,28.191334
        GeoPoint startPoint_init = new GeoPoint(28.191334, 112.98068);
        mapController.setCenter(startPoint_init);
        mMapView.setDrawingCacheEnabled(true);
        mMapView.setUseDataConnection(true);
        mMapView.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.ALWAYS);
        mMapView.setMultiTouchControls(true);
        //是否显示地图数据源
        mMapView.getOverlayManager().getTilesOverlay().setEnabled(true);


        //地图自由旋转
        mRotationGestureOverlay = new RotationGestureOverlay(mMapView);
        mRotationGestureOverlay.setEnabled(true);
        mMapView.getOverlays().add(this.mRotationGestureOverlay);

        //比例尺配置
        final DisplayMetrics dm = getResources().getDisplayMetrics();
        mScaleBarOverlay = new ScaleBarOverlay(mMapView);
        mScaleBarOverlay.setCentred(true);
        mScaleBarOverlay.setAlignBottom(true); //底部显示
        mScaleBarOverlay.setScaleBarOffset(dm.widthPixels / 5, 80);
        mMapView.getOverlays().add(this.mScaleBarOverlay);

        //指南针方向
        mCompassOverlay = new CompassOverlay(this, new InternalCompassOrientationProvider(this),
                mMapView);
        mCompassOverlay.enableCompass();
        mMapView.getOverlays().add(this.mCompassOverlay);

        //设置导航图标
        mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(this),
                mMapView);
        mMapView.getOverlays().add(this.mLocationOverlay);
        mLocationOverlay.enableMyLocation();  //设置可视


    }

    /**
     * 设置地图源
     */
    private void setMapSources() {
        if (NetworkUtils.isConnected(this)) {
            mMapView.setTileSource(GoogleTileSource.AutoNaviVector);
        } else {
//            ToastUtils.showToast("当前无网络，请选择离线地图包");
            if (mMapView.getOverlays().size() <= 0) {
                mapViewOffline();
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        //this will refresh the osmdroid configuration on resuming.
        //if you make changes to the configuration, use
        //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        //Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
        mMapView.onResume(); //needed for compass, my location overlays, v6.0.0 and up
    }

    @Override
    public void onPause() {
        super.onPause();
        //this will refresh the osmdroid configuration on resuming.
        //if you make changes to the configuration, use
        //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        //Configuration.getInstance().save(this, prefs);
        mMapView.onPause();  //needed for compass, my location overlays, v6.0.0 and up
    }


    /**
     * 加载离线地图
     */
    public void mapViewOffline() {
        String strFilepath = Environment.getExternalStorageDirectory().getPath() + "/osmdroid/jiang.sqlite";
        File exitFile = new File(strFilepath);
        String fileName = exitFile.getName();
        if (!exitFile.exists()) {
            mMapView.setTileSource(TileSourceFactory.MAPNIK);
        } else {
            fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (ArchiveFileFactory.isFileExtensionRegistered(fileName)) {
                try {
                    OfflineTileProvider tileProvider = new OfflineTileProvider(new SimpleRegisterReceiver(this), new File[]{exitFile});
                    mMapView.setTileProvider(tileProvider);

                    String source = "";
                    IArchiveFile[] archives = tileProvider.getArchives();
                    if (archives.length > 0) {
                        Set<String> tileSources = archives[0].getTileSources();
                        if (!tileSources.isEmpty()) {
                            source = tileSources.iterator().next();
                            mMapView.setTileSource(FileBasedTileSource.getSource(source));
                        } else {
                            mMapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
                        }

                    } else {
                        mMapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
                    }
                    Toast.makeText(this, "Using " + exitFile.getAbsolutePath() + " " + source, Toast.LENGTH_LONG).show();
                    mMapView.invalidate();
                    return;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                Toast.makeText(this, " did not have any files I can open! Try using MOBAC", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, " dir not found!", Toast.LENGTH_LONG).show();
            }
        }
    }
}
